<template>
  <div class="app-container receipt-container-view">
    <div style="padding: 10px 0;">
      <ReceiptFormFilter
        @on-filter="submitFilterForm"
      />
    </div>
    <div class="button-group">
      <el-button
        v-if="roleCheck(paySetType.rechargeAdd)"
        type="primary"
        :loading="loading"
        @click="openDialog({dialogName: dialogType.addEscrow, props: {}})"
      >
        新增三方平台
      </el-button>
      <el-button
        v-if="roleCheck(paySetType.rechargeStatus)"
        type="primary"
        :disabled="!isChecked"
        :loading="loading"
        @click="openDialog({
          dialogName: dialogType.confirmStatus,
          props: {
            contentProps: constType.openAll,
            cacheData: { row: null, status : constType.statusOpen }
          },
        })"
      >
        批量开启商户
      </el-button>
      <el-button
        v-if="roleCheck(paySetType.rechargeStatus)"
        type="primary"
        :disabled="!isChecked"
        :loading="loading"
        @click="openDialog({
          dialogName: dialogType.confirmStatus,
          props: {
            contentProps: constType.closeAll,
            cacheData: { row: null, status : constType.statusClose }
          },
        })"
      >
        批量关闭商户
      </el-button>
      <div class="open-close" v-if="roleCheck('open-show-merchant')">
        <span>是否开启通道展示：</span>
        <el-switch
          class="switch"
          active-text="开启"
          inactive-text="关闭"
          :active-value="0"
          :inactive-value="1"
          @change="toggleMerchant"
          v-model="status">
        </el-switch>
      </div>
    </div>
    <el-table
      border
      :data="tableData.list"
      v-loading="loading"
      element-loading-text="加载中..."
      class="el-table-align-center"
      :row-class-name="handleTableRowClassName"
      @selection-change="onChangeSelection"
    >
      <el-table-column
        type="selection"
        width="55"
      >
      </el-table-column>
      <el-table-column label="三方平台" prop="channelName" width="180" align="center">
        <template slot-scope="{row}">
          {{row.channelName}}
        </template>
      </el-table-column>
      <el-table-column label="商户号" prop="merchantCode" align="center">
        <template slot-scope="{row}">
          <el-tooltip
            placement="top"
            v-if="row.merchantCode && row.merchantCode.length > constType.ellipsisLen + 5"
          >
            <div slot="content" class="global-table-tooltip-item-view">
              {{row.merchantCode}}
            </div>
            <div class="global-table-single-item-view">{{row.merchantCode}}</div>
          </el-tooltip>
          <div class="global-table-single-item-view" v-else>{{row.merchantCode}}</div>
        </template>
      </el-table-column>
      <el-table-column label="公钥" prop="publicKey" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('recharge-key-show')">
            <el-tooltip
              placement="top"
              v-if="row.publicKey && row.publicKey.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.publicKey}}
              </div>
              <div class="global-table-single-item-view">{{row.publicKey}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.publicKey}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="私钥" prop="privateKey" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('recharge-key-show')">
            <el-tooltip
              placement="top"
              v-if="row.privateKey && row.privateKey.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.privateKey}}
              </div>
              <div class="global-table-single-item-view">{{row.privateKey}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.privateKey}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="请求URL" prop="payUrl" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('recharge-url-show')">
            <el-tooltip
              placement="top"
              v-if="row.payUrl && row.payUrl.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.payUrl}}
              </div>
              <div class="global-table-single-item-view">{{row.payUrl}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.payUrl}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="接收URL" prop="notifyUrl" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('recharge-url-show')">
            <el-tooltip
              placement="top"
              v-if="row.notifyUrl && row.notifyUrl.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.notifyUrl}}
              </div>
              <div class="global-table-single-item-view">{{row.notifyUrl}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.notifyUrl}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="结果URL" prop="resultUrl" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('recharge-url-show')">
            <el-tooltip
              placement="top"
              v-if="row.resultUrl && row.resultUrl.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.resultUrl}}
              </div>
              <div class="global-table-single-item-view">{{row.resultUrl}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.resultUrl}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="每日收款上限" prop="dailyLimit" align="center">
         <template slot-scope="{row}">
          {{row.dailyLimit | currency}}
        </template>
      </el-table-column>
      <el-table-column label="今日已收款金额" prop="successAmount" align="center">
         <template slot-scope="{row}">
          {{row.successAmount | currency}}
        </template>
      </el-table-column>
      <el-table-column label="开关状态" width="90" align="center">
        <template slot-scope="{row}">
          {{row.status === constType.statusOpen ? '已开启' : '已关闭'}}
        </template>
      </el-table-column>
      <el-table-column label="渠道类型" width="90" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.limitType, payEnum.PAY_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center">
      </el-table-column>
      <el-table-column label="操作" width="180px" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button
            v-if="roleCheck(paySetType.rechargeEdit)"
            type="text"
            @click="openDialog({dialogName: dialogType.addEscrow, props: row })"
          >
            编辑
          </el-button>
          <el-button
            v-if="roleCheck(paySetType.rechargeDelete)"
            type="text"
            @click="onClickDeleteItem(row)"
          >
            删除
          </el-button>
          <el-button
            v-if="roleCheck(paySetType.rechargeStatus) && row.status === constType.statusOpen"
            type="text"
            @click="openDialog({
              dialogName: dialogType.confirmStatus,
              props: {
                contentProps: constType.closeSingle,
                cacheData: { row, status : constType.statusClose }
              },
            })"
          >
            关闭
          </el-button>
          <el-button
            v-if="roleCheck(paySetType.rechargeStatus) && row.status === constType.statusClose"
            type="text"
            @click="openDialog({
              dialogName: dialogType.confirmStatus,
              props: {
                contentProps: constType.openSingle,
                cacheData: { row, status : constType.statusOpen }
              },
            })"
          >
            开启
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      >
      </el-pagination>
    </div>
    <ReceiptEditDialog
      v-if="dialogName === dialogType.addEscrow"
      v-model="dialogVisible"
      :row-data="dialogProps"
      @submit="submitFinished"
    />
    <ConfirmStatusDialog
      v-if="dialogName === dialogType.confirmStatus"
      v-model="dialogVisible"
      :rowData="dialogProps"
      @confirm="onToggleStatus"
      footText="注：商户开启后才可以在“三方入款应用”中应用并上架，若是关闭则“三方入款应用”中的商户为关闭状态；关闭后前台也无法展示此三方商户"
    />
  </div>
</template>


<script>

// constants
import { messageType } from '@/const/enum';
import { constType } from '@/const/payEnum';
import { paySetType } from '@/router/payRoutes';

// components
import ReceiptFormFilter from './receiptFormFilter';
import ReceiptEditDialog from './receiptEditDialog';
import ConfirmStatusDialog from './confirmStatusDialog';

// services
import { getRechargeMerchantList, updateRechargeMerchantStatus, delPaymentEscrow } from '@/services/api/payment';
import {
  getShowMerchantApi,
  saveShowMerchantApi,
} from '@/services/api/recharge';

// mixins
import { grid, constsLabel, dialog } from '@/build';

const dialogType = {
  addEscrow: 'receipt-edit-dialog',
  confirmStatus: 'confirm-status-dialog',
};

export default {
  name: 'receipt',
  components: {
    ReceiptFormFilter,
    ReceiptEditDialog,
    ConfirmStatusDialog,
  },
  mixins: [grid, constsLabel, dialog],
  data() {
    return {
      paySetType,
      filters: {
        page: 1,
        size: 20,
      },
      tableData: {},
      tableSelectionList: [],
      dialogType,
      constType,
      status: 0,
    };
  },
  computed: {
    isChecked() {
      return Array.isArray(this.tableSelectionList) && !!this.tableSelectionList.length;
    },
  },
  methods: {
    handleTableRowClassName({ row }) {
      const { dailyLimit, successAmount } = row || {};
      if (successAmount > dailyLimit) {
        return 'finished-row';
      }
      return '';
    },
    onChangeSelection(val) {
      this.tableSelectionList = val;
    },
    getCurrMerchantId(row) {
      if (row && Object.keys(row).length) {
        return `${row.merchantId}`;
      }
      return this.tableSelectionList.map(item => item.merchantId).join(',');
    },
    async onToggleStatus({ row, status }) {
      try {
        this.loading = true;
        const merchantIds = this.getCurrMerchantId(row);
        const [bool, result] = await updateRechargeMerchantStatus({
          merchantIds,
          status,
        });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: `${status === constType.statusClose ? '关闭' : '开启'}成功`,
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      } finally {
        this.loading = false;
      }
    },
    async onClickDeleteItem({ merchantId }) {
      try {
        await this.$confirm('确定要删除三方入款商户吗？', '删除三方入款商户', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const [bool, result] = await delPaymentEscrow({ merchantId });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: '删除成功',
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      }
    },
    toggleMerchant(val) {
      this.$confirm(`确定要${val === 0 ? '开启' : '关闭'}通道展示吗？`, '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.doSave({ action: 'saveShowMerchant' });
      })
        .catch(() => {
          this.status = this.status === 0 ? 1 : 0;
        });
    },
  },
  mounted() {
    this.bindGet(getRechargeMerchantList, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });
    this.bindGet(getShowMerchantApi, 'status', {
      format: data => (data === 'true' ? 0 : 1),
    });
    this.getAll();
    this.bindSave(saveShowMerchantApi, 'saveShowMerchant', 'status', {
      beforeSend: data => ({ status: data }),
    });
  },
};
</script>

<style lang="scss">
  .receipt-container-view {
    .el-table .finished-row {
      background: #ffc55b;
    }
  }
  .button-group{
    display: flex;
    align-items: center;
    .open-close{
      margin-left: 10px;
    }
  }
</style>
